package com.mingtu.jgspatrol.activity;

import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.hjq.gson.factory.GsonFactory;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.base.MyBaseActivity;
import com.mingtu.jgspatrol.bean.TaskDetailsBean;
import com.mingtu.jgspatrol.bean.TaskDetailsInfoBean;
import com.mingtu.jgspatrol.databinding.ActivitySendTaskDetailsBinding;
import com.mingtu.jgspatrol.utils.MyConstant;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class SendTaskDetailsActivity extends MyBaseActivity<ActivitySendTaskDetailsBinding> {
    private ArrayList<String> peopleList = new ArrayList<>();
    private String sourceType;
    private String[] peopleArray = null;
    private String taskId;
    private Timer timer;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_send_task_details;
    }

    @Override
    protected void initView() {
        setModuleTitle("下发详情");
    }

    @Override
    protected void initData() {
        addClickListener(this,  binding.ivEyes, binding.complete);
    }

    @Override
    protected void getData() {
        taskId = getIntent().getStringExtra("taskId");
        sourceType = getIntent().getStringExtra("sourceType");
        if (StringUtils.isEmpty(taskId)) {
            ToastUtils.showLong(getResources().getString(R.string.data_error));
            return;
        }

//        if (!StringUtils.isEmpty(sourceType)) { //从首页待办任务跳转过来 1:巡护任务 2：其他任务
//            getIndexTaskDetails(taskId);
//            complete.setVisibility(View.VISIBLE);
//        } else {
            getTaskDetails(taskId);
//        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_eyes:
                if (peopleArray != null) {
                    if (peopleArray.length > 0) {
                        new XPopup.Builder(this)
                                //                        .maxWidth(600)
                                .maxHeight(1000)
                                .isDarkTheme(false)
                                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                                .asCenterList("接收人员", peopleArray,
                                        new OnSelectListener() {
                                            @Override
                                            public void onSelect(int position, String text) {

                                            }
                                        })
                                .show();
                    }
                }

                break;

            case R.id.complete:
                finishTask();
                break;

        }
    }

    @Override
    protected void onDestroy() {
        peopleList.clear();
        if (timer != null) {
            timer.cancel();
        }
        super.onDestroy();
    }

    /**
     * 任务详情
     *
     * @param id
     */
    private void getTaskDetails(String id) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", id);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_SEND_TASK_DETAILS + "/" + id)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            Gson gson = GsonFactory.getSingletonGson();
                            TaskDetailsBean taskDetailsBean = new TaskDetailsBean();
                            taskDetailsBean = gson.fromJson(result, TaskDetailsBean.class);
                            TaskDetailsBean.AssignmentBean assignmentBean = taskDetailsBean.getAssignment();
                            List<TaskDetailsBean.AssignmentBean.AssignmentUserEntityListBean> listBeans = assignmentBean.getAssignmentUserEntityList(); //接收人员
                            String taskName = assignmentBean.getName();
                            String dealineTime = assignmentBean.getFinishTime();
                            String content = assignmentBean.getMemo();
                            String isFinish = assignmentBean.getIsFinish();


                            if (!StringUtils.isEmpty(taskName)) {
                                binding.tvTaskName.setText(taskName);
                            }

                            if (!StringUtils.isEmpty(dealineTime)) {
                                binding.tvTime.setText(dealineTime);
                            }

                            if (!StringUtils.isEmpty(content)) {
                                binding.tvDetailsInfo.setText(content);
                            }

                            if (listBeans != null) {
                                int size = listBeans.size();
                                if (size > 0) {
                                    String str = "";
                                    peopleArray = new String[size];
                                    for (int i = 0; i < size; i++) {
                                        String name = listBeans.get(i).getName();
                                        peopleArray[i] = name;
                                    }

                                    if (size == 1) {
                                        str = listBeans.get(0).getName();
                                    }
                                    if (size > 1 && size <= 3) {
                                        for (int i = 0; i < size; i++) {
                                            String name = listBeans.get(i).getName();
                                            if (i < listBeans.size() - 1) {
                                                name = name + "，";
                                            }
                                            str += name;
                                        }
                                    }

                                    if (size > 3) {
                                        List<TaskDetailsBean.AssignmentBean.AssignmentUserEntityListBean> myListBeans = listBeans.subList(0, 3);
                                        for (int i = 0; i < myListBeans.size(); i++) {
                                            String name = myListBeans.get(i).getName();
                                            if (i < myListBeans.size() - 1) {
                                                name = name + "，";
                                            }
                                            str += name;
                                        }
                                    }

                                    if (size > 3) {
                                        binding.ivEyes.setVisibility(View.VISIBLE);
                                        binding.tvName.setText(str + "等" + size + "人");
                                    } else {
                                        binding.tvName.setText(str);
                                    }
                                }
                            }

                            if (!StringUtils.isEmpty(isFinish)) {
                                if (isFinish.equals("1")) {
                                    binding.layoutFinish.setVisibility(View.VISIBLE);
                                } else {
                                    binding.layoutFinish.setVisibility(View.GONE);
                                }
                            }

                            int size = listBeans.size();
                            if (size == 1) {
                                TaskDetailsBean.AssignmentBean.AssignmentUserEntityListBean listBean = listBeans.get(0);
                                String completeTime = listBean.getCompleteTime();//2021-08-18 10:43:26
                                binding.tvFinishTime.setText(completeTime + "");
                            } else if (size > 1) {
                                //计算完成时间
                                List<Long> timeList = new ArrayList<>();
                                for (int i = 0; i < listBeans.size(); i++) {
                                    TaskDetailsBean.AssignmentBean.AssignmentUserEntityListBean listBean = listBeans.get(i);
                                    String completeTime = listBean.getCompleteTime();//2021-08-18 10:43:26
                                    long timeMillis = TimeUtils.string2Millis(completeTime);
                                    timeList.add(timeMillis);
                                }
                                long maxTimeMillis = Collections.max(timeList);
                                String endcompleteTime = TimeUtils.millis2String(maxTimeMillis);
                                binding.tvFinishTime.setText(endcompleteTime + "");
                            }
                        }
                    }
                });
    }


    /**
     * 首页任务详情
     *
     * @param id
     */
    private void getIndexTaskDetails(String id) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", id);
        hashMap.put("type", sourceType);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_INDEX_TASK_DETAILS)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            Gson gson = GsonFactory.getSingletonGson();
                            TaskDetailsInfoBean taskDetailsInfoBean = new TaskDetailsInfoBean();
                            taskDetailsInfoBean = gson.fromJson(result, TaskDetailsInfoBean.class);
                            TaskDetailsInfoBean.InfoBean infoBean = taskDetailsInfoBean.getInfo();
                            List<TaskDetailsInfoBean.InfoBean.AssignmentUserEntityListBean> listBeans = infoBean.getAssignmentUserEntityList(); //接收人员
                            String taskName = infoBean.getName();
                            String dealineTime = infoBean.getFinishTime();
                            String content = infoBean.getMemo();


                            if (!StringUtils.isEmpty(taskName)) {
                                binding.tvTaskName.setText(taskName);
                            }

                            if (!StringUtils.isEmpty(dealineTime)) {
                                binding.tvTime.setText(dealineTime);
                            }


                            if (!StringUtils.isEmpty(content)) {
                                binding.tvDetailsInfo.setText(content);
                            }

                            if (listBeans != null) {
                                int size = listBeans.size();
                                if (size > 0) {
                                    String str = "";
                                    peopleArray = new String[size];
                                    for (int i = 0; i < size; i++) {
                                        String name = listBeans.get(i).getName();
                                        peopleArray[i] = name;
                                    }


                                    if (size == 1) {
                                        str = listBeans.get(0).getName();
                                    }
                                    if (size > 1 && size <= 3) {
                                        for (int i = 0; i < size; i++) {
                                            String name = listBeans.get(i).getName();
                                            if (i < listBeans.size() - 1) {
                                                name = name + "，";
                                            }
                                            str += name;
                                        }
                                    }

                                    if (size > 3) {
                                        List<TaskDetailsInfoBean.InfoBean.AssignmentUserEntityListBean> myListBeans = listBeans.subList(0, 3);
                                        for (int i = 0; i < myListBeans.size(); i++) {
                                            String name = myListBeans.get(i).getName();
                                            if (i < myListBeans.size() - 1) {
                                                name = name + "，";
                                            }
                                            str += name;
                                        }
                                    }

                                    if (size > 3) {
                                        binding.ivEyes.setVisibility(View.VISIBLE);
                                        binding.tvName.setText(str + "等" + size + "人");
                                    } else {
                                        binding.tvName.setText(str);
                                    }
                                }
                            }

                        }
                    }
                });
    }


    /**
     * 完成任务操作
     */
    private void finishTask() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", taskId);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_FINISH_TASK__TEM + "/" + taskId)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                ToastUtils.showLong("任务完成！");
                                binding.complete.setVisibility(View.GONE);
                                //实例化Timer类 ,守护线程，不在后台一直运行
                                timer = new Timer(true);
                                timer.schedule(new TimerTask() {
                                    public void run() {
                                        setResult(200);
                                        ActivityUtil.removeActivity(SendTaskDetailsActivity.this);
                                    }
                                }, Constant.TIMER_TIME);

                            }

                        }
                    }
                });
    }
}